import chartOp from '@/common/chart-option.js';
import { $demoi18n } from '@/utils/lang';
import {
  clone, convertValue,
  getColor, getConvertedString,
  getSerieColor, getThemeColors,
  getTooltipMarker, labelLeapOut, numFormat, numFormatToFixed,
  xssFilter,
  xssValueFilter,
  mergeColorBoard,
} from '@/utils/util';
import optionList from './chart-option.json';
import _colorBoard from './color_board.js';
const colorBoard = mergeColorBoard(_colorBoard);

const tooltip = {
  componentStyle: '',
  backgroundColor: '',
  nameColor: '',
  valueColor: '',
  chartWidth: 0,
  bodyWidthPercent: 0,
};

// 获取转换后适当换行的文本
function adjustText(str, singleFontSize = 12) {
  const { chartWidth, bodyWidthPercent } = tooltip;

  const restWidth = (chartWidth * (1 - bodyWidthPercent / 100)) / 2 - 10; // 10是引导线的长度
  const loadNum = Math.floor(restWidth / singleFontSize); // 12 是字体大小
  return getConvertedString(str, loadNum);
}

function formateLabel(params) {
  const valueLabel = params.data.yLabel || numFormat(params.data.trueValue, true);
  const _unit = params.data.yLabel ? '' : params.data._unit;
  const valueStr = `${valueLabel}${_unit} (${params.data.percent}%)`;
  const formatStr = `
  {name|${labelLeapOut(params.trueName || (params.data && params.data.trueName) || params.name, 3)}:}
  {value|${adjustText(valueStr, 6)}}`;
  return formatStr;
}

// 画中间总数
function getTotalSerie(data, property) {
  const { componentStyle, bodyWidthPercent = 50, totalDecimalCount = 2 } = property;
  let sum;
  if (data.sumLabel === undefined) {
    sum = Number(data.sum);
    sum = numFormatToFixed(sum, totalDecimalCount);
  } else {
    sum = data.sumLabel;
  }

  const centerX = bodyWidthPercent / 2;

  const serie = {
    name: 'total',
    type: 'pie',
    radius: [0, 0],
    center: [`${centerX}%`, '50%'],
    hoverOffset: 0,
    label: {
      show: true,
      position: 'center',
      formatter: [`{title|${sum}}`].join('\n\n'),
      rich: {
        title: {
          fontSize: convertValue(18, 12),
          color: colorBoard[componentStyle].label.title.color,
          fontFamily: 'Arial',
        },
        subTitle: {
          fontSize: convertValue(16, 12),
          color: colorBoard[componentStyle].label.subTitle.color,
          fontFamily: 'Arial',
        },
      },
    },
    data: [
      {
        name: $demoi18n('message.total'),
        value: data.sum,
      },
    ],
  };
  return serie;
}

/**
 * 设置图表数据 series legend等
 * @param {*} option 图表option
 * @param {*} data 图表数据参数
 */
function setChartData(option, data, property) {
  const { seriesData } = data;
  const { componentStyle, color, bodyWidthPercent = 50 } = property;
  const colors = getThemeColors(color, colorBoard[componentStyle].colorGroup);
  const colorGroupLength = colors.length;

  const centerX = bodyWidthPercent / 2;
  const radiusIn = bodyWidthPercent * 0.7;
  const radiusOut = bodyWidthPercent;

  const serie = {
    name: '', type: 'pie', center: [`${centerX}%`, '50%'],
    radius: [`${radiusIn}%`, `${radiusOut}%`],
    width: '100%', height: '100%', avoidLabelOverlap: true,
    label: {
      show: false, position: 'outside', overflow: 'truncate',
      formatter: formateLabel,
      rich: {
        value: {
          color: colorBoard[componentStyle].label.value0.color,
        },
        name: {
          color: colorBoard[componentStyle].label.title0.color,
        },
      },
    },
    labelLine: { length: 0, length2: 10 },
    data: [],
  };
  const legends = chartOp.formatPieLegendData(data, property);
  const legendTextStyle = chartOp.formatPieLegendTextStyle(property, option);
  seriesData.forEach((item, index) => {
    const s = { ...item, trueName: item.name, name: legends[index], orgData: seriesData[index].orgData };
    let colorValue;
    if (typeof color === 'string') {
      colorValue = getSerieColor(colors[index % colorGroupLength]);
    } else {
      const _color = getColor(color, item.name);
      colorValue = getSerieColor(_color);
    }
    s.itemStyle = {
      color: colorValue,
    };
    serie.data.push(s);
  });

  option.series.push(serie);
  if (property.showTotal !== false) {
    option.series.push(getTotalSerie(data, property));
  }
  const { textStyle } = option.legend;
  option.legend = {
    ...option.legend,
    textStyle: {
      ...textStyle,
      rich: {
        a: legendTextStyle,
        b: { ...legendTextStyle, color: colorBoard[componentStyle].label.value0.color },
      },
    },
    data: legends,
  };
}

/**
 * 自定义图表提示框
 * @param {*} params  echart自带参数
 */
function formateTooltip(params) {
  const empty = '';
  if (!chartOp.isOrgTooltipVisible()) {
    return empty;
  }
  if (params.seriesIndex === 1) {
    return empty;
  } // 总数不用tooltip

  const { backgroundColor, nameColor, valueColor } = tooltip;
  xssFilter(params, ['name']);
  const valueLabel = params.data.yLabel ? xssValueFilter(params.data.yLabel) : numFormat(params.data.trueValue, true);
  const formatStr = `
    <div class='tooltip_pie' style='padding:5px 7px; border:'>
      ${getTooltipMarker(params.color)}
      <span style='color:${nameColor}'>${params.trueName ||
    (params.data && params.data.trueName) ||
    params.name}:</span>
      <span style='color:${valueColor}'>${valueLabel} (${params.data.percent}%)</span>
    <div/>
    <div class='tooltip_pie_triangle' style='border-right-color: ${backgroundColor}'></div>
  `;
  return formatStr;
}

/**
 * 将接口数据转换为echart方便使用的数据
 * @param {*} data 接口数据
 */
export const convertData = function(data, property) {
  return chartOp.convertPieData(data, property, 'basic-pie');
};

/**
 * 设置图表整体option
 * @param {*} data 图表数据
 * @param {*} property 配置页面中属性面板中的参数
 */
export const setChartOption = (data, property, extraConfig = {}) => {
  let option = clone(optionList);
  option = chartOp.setChartPieOption({
    option,
    data,
    extraConfig,
    property,
    tooltip,
    formateTooltip,
    setChartData,
    colorBoard,
  }, 'basic-pie');
  return option;
};
